var api = require('../config/api.js');
var wxcache = require('./wxcache.js');
var postfix = '_deadtime';
/*
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
*/
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}  
/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
  if (wxcache.get("userInfo") && wxcache.get("userInfo").id){
    url = url + "?p_u=" + wxcache.get("userInfo").id
  }

  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'r_s':'emhvbmd5b3U='
      },
      success: function (res) {

        if (res.statusCode == 200) {

          if (res.data.errno == 401) {
            //需要登录后才可以操作
 
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      //fail 执行当做断网处理
      fail: function (err) {
        wx.showToast({
          title: '网络不稳定...',
          icon:'loading',
          duration:5000
        }) 
        console.log(err)
      }
    })
  });
}


/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          console.log(res)
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      withCredentials: true,
      success: function (res) {
        console.log(res)
        resolve(res);
      },
      fail: function (err) {
        reject(err);
      }
    })
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}


//数据转化  
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//合并json
function mergeJson(jsonbject1, jsonbject2) {
  var resultJsonObject = {};
  for (var attr in jsonbject1) {
    resultJsonObject[attr] = jsonbject1[attr];
  }
  for (var attr in jsonbject2) {
    resultJsonObject[attr] = jsonbject2[attr];
  }
  return resultJsonObject;
};



/**
 * 页面Loading显示、隐藏、弹框显示
 */
var Modal = (function () {

  var priToast,       // 显示弹框Toast
    priLoading,     // 显示loading
    hidePriLoading; // 隐藏loading

  /**
   * 显示弹框
   * options 自定义配置参数
   */
  priToast = function (options) {
    // 调用api显示弹框
    wx.showToast({
      title: options.content,
      icon: options.type,
      duration: options.duration,
      mask: true
    })
  };

  /**
   *  显示loading
   */
  priLoading = function () {
    // 调用微信API显示loading
    wx.showLoading({
      title: "加载中...",
      mask: true
    });
  };

  /**
   *  隐藏loading
   */
  hidePriLoading = function () {
    // 调用微信API隐藏loading
    setTimeout(function () {
      wx.hideLoading()
    }, 1000)
  };

  return {
    priToast: priToast,
    priLoading: priLoading,
    hidePriLoading: hidePriLoading
  }

})();

/**
 * 页面跳转方法,分为跳转page、tabBar页面，返回上一级
 */
var PageContent = (function () {

  var loadNavigate,       // 跳转非tabBar页面
    goBack,             // 返回上一级
    loadNavTabBar;      // 跳转tabBar页面

  /**
   * 跳转非tabBar页面
   * @pram url 跳转路径
   */
  loadNavigate = function (url) {
    wx.navigateTo({
      url: url
    })
  };

  /**
   * 返回上一页
   * @pram delta 跳转层数
   */
  goBack = function (delta) {
    wx.navigateBack({
      delta: delta       //返回的页面层数
    })
  };

  /**
   * 跳转tabBar页面
   * @pram url路径
   */
  loadNavTabBar = function (url) {
    wx.switchTab({
      url: url
    });
  };

  return {
    loadNavigate: loadNavigate,
    goBack: goBack,
    loadNavTabBar: loadNavTabBar
  }

})();



module.exports = {
  mergeJson,
  formatTime,
  request,
  redirect,
  showErrorToast,
  checkSession,
  login,
  getUserInfo,
  Modal,
  PageContent

}


